<template>
  <div class="routes-page" v-loading="loading">
    <page-banner title="旅游攻略" subtitle="探索专业策划的特色行程" />

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="container">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select
              v-model="filters.theme"
              placeholder="主题筛选"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="item in filterOptions.themes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span class="option-label">
                  <el-icon><Picture /></el-icon>
                  {{ item.label }}
                </span>
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="filters.difficulty"
              placeholder="难度等级"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="item in filterOptions.difficulties"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span class="option-label">
                  <el-icon><Histogram /></el-icon>
                  {{ item.label }}
                </span>
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="filters.duration"
              placeholder="行程天数"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="item in filterOptions.durations"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span class="option-label">
                  <el-icon><Timer /></el-icon>
                  {{ item.label }}
                </span>
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="filters.sort"
              placeholder="排序方式"
              @change="handleFilter"
            >
              <el-option
                v-for="item in sortOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span class="option-label">
                  <el-icon><Sort /></el-icon>
                  {{ item.label }}
                </span>
              </el-option>
            </el-select>
          </el-col>
        </el-row>

        <!-- 已选筛选条件展示 -->
        <div class="selected-filters" v-if="hasFilters">
          <div class="selected-tags">
            <el-tag
              v-for="(value, key) in activeFilters"
              :key="key"
              closable
              @close="clearFilter(key)"
            >
              {{ getFilterLabel(key, value) }}
            </el-tag>
          </div>
          <el-button type="primary" link @click="resetFilters">
            清除全部
            <el-icon class="el-icon--right"><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 路线列表 -->
    <div class="routes-section">
      <div class="container">
        <el-row :gutter="30">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            v-for="route in routes"
            :key="route.id"
          >
            <div class="route-card" @click="viewRoute(route.id)">
              <div class="card-image">
                <img :src="getImageUrl(route.imageUrl)" :alt="route.title" />
                <div class="card-overlay">
                  <div class="tags">
                    <el-tag size="small" :style="getTagStyle(route.theme)">{{
                      route.theme
                    }}</el-tag>
                    <el-tag size="small" type="warning">{{
                      route.difficulty
                    }}</el-tag>
                  </div>
                </div>
              </div>
              <div class="card-content">
                <h3>{{ route.title }}</h3>
                <p class="description">{{ route.description }}</p>
                <div class="route-features">
                  <el-tag
                    v-for="(feature, index) in route.features"
                    :key="index"
                    size="small"
                    :style="getFeatureStyle(index)"
                  >
                    {{ feature }}
                  </el-tag>
                </div>
                <div class="card-footer">
                  <div class="duration">
                    <el-icon><Timer /></el-icon>
                    <span>{{ route.duration }}天</span>
                  </div>
                  <div class="price">
                    <span class="label">￥</span>
                    <span class="amount">{{ route.price }}</span>
                    <span class="unit">起</span>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 分页器 -->
        <div class="pagination-wrapper" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            background
            layout="prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 修改导入部分
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import PageBanner from "@/components/PageBanner.vue";
import { ElMessage } from "element-plus";
import { Timer, Picture, Histogram, Sort, Delete } from "@element-plus/icons-vue";
import { getImageUrl } from "@/utils/format";
import { pageRoutes, getRouteFilterOptions } from "@/api/route";

const router = useRouter();
const loading = ref(false);
const routes = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(9); // 添加页面大小控制

// 筛选条件
const filters = ref({
  theme: "",
  difficulty: "",
  duration: "",
  price: "",
  sort: "default",
});

// 筛选选项
const filterOptions = ref({
  themes: [],
  difficulties: [],
  durations: []
});

// 添加排序选项
const sortOptions = [
  { value: 'default', label: '默认排序' },
  { value: 'priceAsc', label: '价格从低到高' },
  { value: 'priceDesc', label: '价格从高到低' },
  { value: 'popular', label: '人气优先' },
  { value: 'newest', label: '最新上线' }
];

// 获取筛选选项
const fetchFilterOptions = async () => {
  try {
    const options = await getRouteFilterOptions();
    filterOptions.value = options;
  } catch (error) {
    console.error("获取筛选选项失败:", error);
  }
};

// 获取路线列表
const fetchRoutes = async () => {
  loading.value = true;
  try {
    const params = {
      theme: filters.value.theme || undefined,
      difficulty: filters.value.difficulty || undefined,
      duration: filters.value.duration ? parseInt(filters.value.duration) : undefined,
      sort: filters.value.sort === 'default' ? undefined : filters.value.sort
    };

    console.log('请求参数:', params);
    const result = await pageRoutes(currentPage.value, pageSize.value, params);
    
    console.log('接口响应:', result);
    if (result) {
      routes.value = result.records || [];
      total.value = result.total || 0;
    } else {
      routes.value = [];
      total.value = 0;
      ElMessage.warning('获取数据失败');
    }
  } catch (error) {
    console.error("获取路线列表失败:", error);
    ElMessage.error("获取数据失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 查看路线详情
const viewRoute = (id) => {
  router.push(`/route/${id}`);
};

// 页码改变
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchRoutes();
  window.scrollTo({ top: 0, behavior: "smooth" });
};

const getTagStyle = (theme) => {
  const styles = {
    摄影创作: { bg: "#e6fffb", text: "#13c2c2" },
    户外探险: { bg: "#fff0f6", text: "#eb2f96" },
    文化体验: { bg: "#f6ffed", text: "#52c41a" },
    休闲度假: { bg: "#fff7e6", text: "#fa8c16" },
  };
  const style = styles[theme] || { bg: "#f5f5f5", text: "#666666" };
  return {
    backgroundColor: style.bg,
    color: style.text,
    border: "none",
  };
};

const getFeatureStyle = (index) => {
  const colors = ["#e6fffb", "#fff0f6", "#f0f5ff", "#f6ffed"];
  return {
    backgroundColor: colors[index % colors.length],
    color: "#666666",
    border: "none",
    marginRight: "8px",
    marginBottom: "8px",
  };
};

// 计算是否有选中的筛选条件
const hasFilters = computed(() => {
  return Object.values(filters.value).some(
    (val) => val !== "" && val !== "default"
  );
});

// 获取当前激活的筛选条件
const activeFilters = computed(() => {
  return Object.entries(filters.value).reduce((acc, [key, value]) => {
    if (value && value !== "default") {
      acc[key] = value;
    }
    return acc;
  }, {});
});

// 获取筛选标签显示文本
const getFilterLabel = (key, value) => {
  const options = {
    theme: filterOptions.themes,
    difficulty: filterOptions.difficulties,
    duration: filterOptions.durations,
    sort: sortOptions,
  };

  const option = options[key]?.find((item) => item.value === value);
  return `${getFilterName(key)}: ${option?.label || value}`;
};

// 获取筛选类型名称
const getFilterName = (key) => {
  const names = {
    theme: "主题",
    difficulty: "难度",
    duration: "天数",
    sort: "排序",
  };
  return names[key] || key;
};

// 清除单个筛选条件
const clearFilter = (key) => {
  filters.value[key] = "";
  handleFilter();
};

// 重置所有筛选条件
const resetFilters = () => {
  filters.value = {
    theme: "",
    difficulty: "",
    duration: "",
    sort: "default",
  };
  handleFilter();
};

// 处理筛选
const handleFilter = async () => {
  currentPage.value = 1; // 重置页码
  await fetchRoutes();
};

onMounted(async () => {
  await fetchFilterOptions();
  await fetchRoutes();
});
</script>

<style scoped>
.routes-page {
  background: var(--light-bg);
}

.filter-section {
  background: white;
  padding: 20px 0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: var(--header-height);
  z-index: 10;
}

.routes-section {
  padding: 40px 0;
}

.route-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.route-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  margin-bottom: 20px;
}

.el-pagination {
  --el-pagination-button-bg-color: white;
}

@media (max-width: 768px) {
  .pagination-wrapper {
    margin-top: 20px;
  }
}

.card-image {
  height: 220px;
  position: relative;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.route-card:hover .card-image img {
  transform: scale(1.1);
}

.card-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.2),
    rgba(0, 0, 0, 0.6)
  );
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.route-card:hover .card-overlay {
  opacity: 1;
}

.card-content {
  padding: 20px;
}

.card-content h3 {
  margin: 0 0 10px;
  font-size: 1.2rem;
  color: var(--text-color);
}

.description {
  color: var(--text-color-secondary);
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.route-features {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px dashed var(--border-color);
}

.duration {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--text-color-secondary);
  font-size: 0.9rem;
}

.price {
  color: #ff6b6b;
}

.price .label {
  font-size: 0.9rem;
}

.price .amount {
  font-size: 1.3rem;
  font-weight: bold;
  margin: 0 2px;
}

.price .unit {
  font-size: 0.9rem;
  opacity: 0.8;
}

@media (max-width: 768px) {
  .filter-section {
    position: static;
    padding: 15px;
  }

  .routes-section {
    padding: 20px 0;
  }
}

/* 添加筛选区域样式 */
.selected-filters {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px dashed var(--border-color);
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.option-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-label .el-icon {
  font-size: 16px;
  color: var(--text-color-secondary);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .el-col {
    margin-bottom: 15px;
  }

  .selected-filters {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .selected-tags {
    width: 100%;
  }
}
</style>